package org.example.filter;

import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.utils.CurrentHolder;
import org.example.utils.JwtUtils;

import java.io.IOException;
@WebFilter(urlPatterns = "/*")
@Slf4j
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取请求路径
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        //判断是否是登陆请求
        if(requestURI.contains("/login")){
            log.info("登陆请求");
            filterChain.doFilter(request,response);
            return;
        }
        //获取请求头中的token
        String token = request.getHeader("token");
        //判断token是否为空，不为空则放行，为空则重定向到登陆页面
        if(token == null || token.isEmpty()){
            log.info("token为空，返回401");
            response.setStatus(401);
            return;
        }
        //校验令牌
        try {
            Claims claims = JwtUtils.parseToken(token);
            Integer empId = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(empId);
            log.info("当前员工id为：{},将其存入ThreadLocal",empId);
        } catch (Exception e) {
            log.info("令牌非法，返回401");
            response.setStatus(401);
            return;
        }
        //放行
        log.info("令牌合法，放行");
        filterChain.doFilter(request,response);
        CurrentHolder.remove();
    }

}
